package com.zslibrary.Protocol;

import android.content.Context;
import android.util.SparseArray;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.zslibrary.BusMaster.MyLanguage;
import com.zslibrary.Structure.LocalAdjustmentStruct;
import com.zslibrary.Structure.UserAdjustmentStruct;
import com.zslibrary.Tools.ZSLog;

public class Adjustments {
    //    private static SparseArray<LocalAdjustmentStruct[]> LocalAdjustment = new SparseArray<LocalAdjustmentStruct[]>();
    private static SparseArray<LocalAdjustmentStruct> CalibrationAdjustment = new SparseArray<LocalAdjustmentStruct>();
    private static SparseArray<LocalAdjustmentStruct[]> ComponentAdjustment = new SparseArray<LocalAdjustmentStruct[]>();
    private static SparseArray<LocalAdjustmentStruct> OptionAdjustment = new SparseArray<LocalAdjustmentStruct>();
    private static List<UserAdjustmentStruct> UserAdjustments = new ArrayList<>();
    private static Boolean isInitialized = false;

    public static Boolean initAdjustment(Context context, String configPath, UserAdjustmentStruct[] uAdjustments) {
        if (!isInitialized) {
            isInitialized = true;
            BufferedReader reader = null;
            try {
                StringBuilder content = new StringBuilder();
                FileReader adjFile = new FileReader(configPath + "/LocalAdjustments.json");
                reader = new BufferedReader(adjFile);
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line);
                }
                JSONArray jsonArray = new JSONArray(content.toString());
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject compAdjsJson = jsonArray.getJSONObject(i);
                    int component = compAdjsJson.getInt("component");
                    if (!compAdjsJson.isNull("adjustments")) {
                        JSONArray adjsJson = compAdjsJson.getJSONArray("adjustments");
                        List<LocalAdjustmentStruct> compAdjs = new ArrayList<>();
//                        LocalAdjustmentStruct[] tempAdjs = new LocalAdjustmentStruct[adjsJson.length()];
//                        int compAdjLen=0;
                        for (int j = 0; j < adjsJson.length(); j++) {
                            JSONObject adj = adjsJson.getJSONObject(j);
                            LocalAdjustmentStruct tempAdj = new LocalAdjustmentStruct();
                            tempAdj.adjustmentId = adj.getInt("adjustment");
                            tempAdj.decPoint = adj.getInt("decPoint");
                            tempAdj.minimum = adj.getInt("minimum");
                            tempAdj.maxmum = adj.getInt("maximum");
                            tempAdj.value = adj.getInt("value");
                            tempAdj.name = (MyLanguage.getLanguage()==0?adj.getString("name_zh"):adj.getString("name_en"));
                            tempAdj.unitType = adj.getString("unitType");
                            tempAdj.type = adj.getInt("type");
                            if ((tempAdj.type & 1) == 1)
//                                tempAdjs[compAdjLen++] = tempAdj;   /*component adjustment*/
                                compAdjs.add(tempAdj);
                            else if ((tempAdj.type & 4) == 4) {
                                CalibrationAdjustment.put(component, tempAdj);  /*calibration adjustment*/
                                continue;
                            } else if ((tempAdj.type & 2) == 2) {
                                /*TODO:暂时不添加*/
                                continue;
                            } else if ((tempAdj.type & 8) == 8) {
                                OptionAdjustment.put(component, tempAdj);
                                continue;
                            }

                        }
//                        LocalAdjustment.put(component, tempAdjs);
//                        ComponentAdjustment.put(component, tempAdjs);
                        ComponentAdjustment.put(component, compAdjs.toArray(new LocalAdjustmentStruct[compAdjs.size()]));
                    }
//                    else
////                        LocalAdjustment.put(component, null);
//                        ComponentAdjustment.put(component, null);
                }
                setAllUserAdjustment(uAdjustments);
            } catch (Exception e) {
                ZSLog.e(e.toString());
            } finally {
                try {
                    reader.close();
                } catch (Exception e) {
                    /*TODO:log*/
                }
            }
//            dbHelper = new UserAdjustmentDatabase(context, "UserADJ.db", null, 1);
//            dbHelper.getWritableDatabase();
        }
        return true;
    }

    public static List<UserAdjustmentStruct> getUserAdjustments() {
        /*UserAdjustmentStruct[] userAdjustments = null;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from user_adj", null);
        if ((cursor.getCount() >= 0) && cursor.moveToFirst()) {
            userAdjustments = new UserAdjustmentStruct[cursor.getCount()];
            int arr_ptr = 0;
            do {
                UserAdjustmentStruct user_adj = new UserAdjustmentStruct();
                user_adj.adjustmentId = (byte) cursor.getInt(cursor.getColumnIndex("adjId"));
                user_adj.componentId = (short) cursor.getInt(cursor.getColumnIndex("component"));
                user_adj.productId = (short) cursor.getInt(cursor.getColumnIndex("product"));
                user_adj.fluid = (byte) cursor.getInt(cursor.getColumnIndex("fluid"));
                user_adj.value = (short) cursor.getInt(cursor.getColumnIndex("value"));
                userAdjustments[arr_ptr++] = user_adj;
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return userAdjustments;*/
        return UserAdjustments;
    }

    public static void setAllUserAdjustment(UserAdjustmentStruct[] adjustment) {
        if ((adjustment != null) && (adjustment.length > 0)) {
//            UserAdjustments= Arrays.asList(adjustment);
            UserAdjustments.clear();
            Collections.addAll(UserAdjustments, adjustment);
        }
    }

    public static void addUserAdjustment(UserAdjustmentStruct adjustment) {
        /*SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query("user_adj", new String[]{"id"}, "adjId=? and component=?", new String[]{String.valueOf(adjustment.adjustmentId), String.valueOf(adjustment.componentId)}, null, null, null);
        if (cursor.getCount() == 0) {
            ContentValues values = new ContentValues();
            values.put("adjId", adjustment.adjustmentId);
            values.put("component", adjustment.componentId);
            values.put("fluid", adjustment.fluid);
            values.put("product", adjustment.productId);
            values.put("value", adjustment.value);
            db.insert("user_adj", null, values);
            values.clear();
        } else {
            ContentValues values = new ContentValues();
            values.put("fluid", adjustment.fluid);
            values.put("product", adjustment.productId);
            values.put("value", adjustment.value);
            db.update("user_adj", values, "adjId=? and component=?", new String[]{String.valueOf(adjustment.adjustmentId), String.valueOf(adjustment.componentId)});
        }
        cursor.close();
        db.close();*/
        for (int i = 0; i < UserAdjustments.size(); i++) {
            if ((UserAdjustments.get(i).componentId == adjustment.componentId) && (UserAdjustments.get(i).adjustmentId == adjustment.adjustmentId)) {
                UserAdjustmentStruct adj = new UserAdjustmentStruct();
                adj.componentId = adjustment.componentId;
                adj.adjustmentId = adjustment.adjustmentId;
                adj.value = adjustment.value;
                adj.fluid = adjustment.fluid;
                adj.productId = adjustment.productId;
                UserAdjustments.set(i, adj);
                return;
            }
        }
        UserAdjustments.add(adjustment);
    }

    public static LocalAdjustmentStruct[] getLocalAdjustment(int component) {
        LocalAdjustmentStruct[] ret;
//        ret = LocalAdjustment.get((component / 100) * 100);
        ret = ComponentAdjustment.get((component / 100) * 100);
        return ret;
    }

    public static LocalAdjustmentStruct[] getAdjustment(int componentId) {
        LocalAdjustmentStruct[] localAdjs = ComponentAdjustment.get((componentId / 100) * 100);
        if (localAdjs == null) return null;

        LocalAdjustmentStruct[] result = new LocalAdjustmentStruct[localAdjs.length];
        List<UserAdjustmentStruct> userAdjs = getUserAdjustments();
        for (int i = 0; i < result.length; i++) {
            result[i] = localAdjs[i].clone();
            if (userAdjs == null) continue;

            LocalAdjustmentStruct adj = result[i];
            for (UserAdjustmentStruct userAdj : userAdjs) {
                if (userAdj.componentId == componentId && userAdj.adjustmentId == adj.adjustmentId) {
                    adj.value = userAdj.value;
                    break;
                }
            }
        }
        return result;
    }

    public static LocalAdjustmentStruct getCalibrationAdjustment(int component) {
        LocalAdjustmentStruct result = CalibrationAdjustment.get(component / 100 * 100);
        return result;
    }
}
